package com.dji.sdk.self.internal.services;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

//import com.amap.api.maps2d.model.LatLng;
import com.dji.sdk.self.internal.connection.SendHttp;
import com.dji.sdk.self.internal.controller.DJISampleApplication;
import com.dji.sdk.self.internal.model.UavCondition;
import com.dji.sdk.self.internal.model.Urls;
import com.dji.sdk.self.internal.network.RetrofitUtil;
import com.dji.sdk.self.internal.utils.ToastUtils;
import com.google.gson.Gson;
//import com.ejlchina.data.Mapper;
//import com.ejlchina.okhttps.HttpResult;
//import com.ejlchina.okhttps.OkHttps;
//import com.ejlchina.okhttps.OnCallback;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import dji.common.airlink.SignalQualityCallback;
import dji.common.battery.BatteryState;
import dji.common.error.DJIError;
import dji.common.flightcontroller.FlightControllerState;
import dji.common.flightcontroller.RTKState;
import dji.common.remotecontroller.Information;
import dji.common.util.CommonCallbacks;
import dji.sdk.airlink.AirLink;
import dji.sdk.base.BaseProduct;
import dji.sdk.battery.Battery;
import dji.sdk.camera.VideoFeeder;
import dji.sdk.flightcontroller.FlightController;
import dji.sdk.flightcontroller.RTK;
import dji.sdk.products.Aircraft;
import dji.sdk.remotecontroller.RemoteController;
import dji.sdk.sdkmanager.DJISDKManager;
import dji.sdk.sdkmanager.LiveStreamManager;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static java.lang.Thread.sleep;

public class SendService extends Service {


    private class MyThread extends  Thread{

    }

    //回传的数据
    private double pitch;
    private double roll;
    private double yaw;
    private double height;
    private float distance;
    private double horizontalSpeed;
    private float verticalSpeed;
    private int voltage;
    private int current;
    private float batteryTemp;
    private int batteryCapacity;//电池容量
    private int uavPower;//飞机电量
    private int remotePower;
    private int remoteSignal;
    private int graphSignal;
    private String serialNumber;
    private UavCondition uavCondition;
    private String streamUrl;
//    private LatLng nanjing ;
    private double latitude = 32 ;
    private double longitude = 181;



    //无人机需要获取的数据所需对象
    private static BaseProduct mProduct;
    private FlightController mFlightController;//
    private Battery battery;//电池
    private RemoteController remoteController;//遥控器
    private RTK rtk;
    private AirLink airLink;
    private LiveStreamManager.OnLiveChangeListener listener;

    //处理注册登录
    private SharedPreferences token;
    private SharedPreferences.Editor editor;
    private String loginToken;
    private long freshTokenAt,accessTokenAt;
    private long now;
    private String name;
    private boolean isLogin;
    private SendHttp sendHttp;

    BaseProduct product = DJISDKManager.getInstance().getProduct();

    //开始无人机数据的初始化
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==100){
                if(product!=null&&product.isConnected()){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendInformation();
                        }
                    }).start();
                }else{
                    ToastUtils.setResultToToast("请连接无人机！");
                }


            }
        }
    };

    Timer timer = new Timer();;
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            Message message = new Message();
            message.what = 100;
            handler.sendMessage(message);
        }
    };

    //获取无人机
    public static synchronized BaseProduct getProductInstance() {
        if (null == mProduct) {
            mProduct = DJISampleApplication.getProductInstance();
        }
        return mProduct;
    }


    private CallBack callback = null;

    public void setCallback(CallBack callback) {
        this.callback = callback;
    }

    public class MyBinder extends android.os.Binder{
        public SendService getService(){
            return SendService.this;
        }
    }
    public SendService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        token = getSharedPreferences("LoginToken", Activity.MODE_PRIVATE);
        now = System.currentTimeMillis()+6000;
        name = token.getString("username",null);
        loginToken = token.getString("loginToken",null);
        freshTokenAt = token.getLong("refreshTokenExpiresAt",0);
        accessTokenAt = token.getLong("accessTokenExpiresAt",0);
        initFlightController();
        return new MyBinder();

    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("SendService","onDestroy");
    }


    private void initFlightController(){
        BaseProduct product = DJISDKManager.getInstance().getProduct();
        if (product != null && product.isConnected()) {
            if (product instanceof Aircraft) {
                mFlightController = ((Aircraft) product).getFlightController();
                battery = product.getBattery();
                remoteController = ((Aircraft) product).getRemoteController();
                rtk = mFlightController.getRTK();
                airLink = product.getAirLink();
                uavCondition = new UavCondition();
                sendHttp = new SendHttp(this);
            }
        }
        if (mFlightController != null) {
            mFlightController.setStateCallback(
                    new FlightControllerState.Callback() {
                        @Override
                        public void onUpdate(FlightControllerState djiFlightControllerCurrentState) {
                            DecimalFormat format = new DecimalFormat("0.000000");
                            latitude =Double.valueOf(format.format(djiFlightControllerCurrentState.getAircraftLocation().getLatitude()));
                            longitude =Double.valueOf(format.format(djiFlightControllerCurrentState.getAircraftLocation().getLongitude()));
                            height = djiFlightControllerCurrentState.getAircraftLocation().getAltitude();
                            pitch = djiFlightControllerCurrentState.getAttitude().pitch;
                            roll = djiFlightControllerCurrentState.getAttitude().roll;
                            yaw = djiFlightControllerCurrentState.getAttitude().yaw;
                            horizontalSpeed = getHorizontalSpeed(djiFlightControllerCurrentState.getVelocityX(),djiFlightControllerCurrentState.getVelocityY());
                            verticalSpeed = djiFlightControllerCurrentState.getVelocityZ();
                            uavCondition.setHeight(height);
                            uavCondition.setHorizontalSpeed(horizontalSpeed);
                            if(!Double.isNaN(latitude)){
                                uavCondition.setLatitude(latitude);
                            }
                            if(!Double.isNaN(longitude)){
                                uavCondition.setLongitude(longitude);
                            }
                            uavCondition.setPitch(pitch);
                            uavCondition.setYaw(yaw);
                            uavCondition.setRoll(roll);
                            uavCondition.setVerticalSpeed(verticalSpeed);

                            //图传信号，Mbps为单位
                            uavCondition.setGraphSignal(VideoFeeder.getInstance().getTranscodingDataRate());
                        }
                    });
            mFlightController.getSerialNumber(new CommonCallbacks.CompletionCallbackWith<String>() {
                @Override
                public void onSuccess(String s) {
                    serialNumber = s;
                    uavCondition.setSerialNumber(serialNumber);
                }

                @Override
                public void onFailure(DJIError djiError) {
                    ToastUtils.setResultToToast("getSerialNumber failed: " + djiError.getDescription());
                }
            });



        }


        if(airLink!=null){
            //遥控器信号
            airLink.setUplinkSignalQualityCallback(new SignalQualityCallback() {
                @Override
                public void onUpdate(int i) {
                    uavCondition.setRemoteSignal(i);
                }
            });
            //图传信号
            airLink.setDownlinkSignalQualityCallback(new SignalQualityCallback() {
                @Override
                public void onUpdate(int i) {
                    uavCondition.setGraphSignal(i);
                }
            });
        }

        if (battery != null && battery.isConnected()) {
            battery.setStateCallback(new BatteryState.Callback() {
                @Override
                public void onUpdate(BatteryState batteryState) {
                    voltage = batteryState.getVoltage();
                    current = batteryState.getCurrent();
                    batteryTemp = batteryState.getTemperature();
                    batteryCapacity = batteryState.getFullChargeCapacity();
                    uavPower = batteryState.getChargeRemaining();
//                    int setCurrent = uavPower/batteryCapacity;
                    uavCondition.setBatteryCapacity(batteryCapacity);
                    uavCondition.setBatteryTemp(batteryTemp);
                    uavCondition.setCurrent(current);
                    uavCondition.setVoltage(voltage);
                    uavCondition.setUavPower(uavPower);
                }
            });
        }

        if (rtk != null&&rtk.isConnected() && rtk.isRTKHealthy()  ) {
            rtk.setStateCallback(new RTKState.Callback() {
                @Override
                public void onUpdate(RTKState rtkState) {
                    distance = rtkState.getDistanceToHomePoint();
                    uavCondition.setDistance(distance);
                }
            });
        }
        if(product instanceof Aircraft){
            timer.schedule(task,500,1500);
        }



    }



    private double getHorizontalSpeed(float volX,float volY){
        return  Math.sqrt(Math.pow(volX,2)+Math.pow(volY,2));

    }



    private void sendInformation(){
        Log.i("GaodeMapActivity",uavCondition.toString());
        if(now+6000>freshTokenAt||loginToken==null){
            ToastUtils.setResultToToast("请登录账号！");
            editor = token.edit();
            editor.putString("login","false");
            editor.putString("loginToken",null);
            isLogin = false;
            stopSelf();
        }
        else{
            if(now>accessTokenAt){
                try {
                    refreshToken();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(uavCondition!=null) {
            callback.onDataChanged(uavCondition);
           sendHttp.sendASyncInformations(uavCondition);
        }
    }



    private void refreshToken() throws IOException {

        RetrofitUtil.getInstance().getApi()
               .getFreshToken(0,loginToken)
                .enqueue(new retrofit2.Callback<ResponseBody>() {
                    @Override
                    public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                        try {
                            String res = response.body().string();
                            Log.i("SendHttp",res);
                            Gson gson = new Gson();
                            Map result = gson.fromJson(res, Map.class);
                            String newAccessToken = (String) result.get("token");
                            // 因为发生了请求，当前时间已经变化，所有重新获取时间
                            long now2 = System.currentTimeMillis();
                            loginToken = newAccessToken;
                            // 保存到 SharedPreferences
                            token.edit()
                                    .putString("loginToken", newAccessToken)
                                    .putLong("refreshTokenExpiresAt", 86400 * 1000 + now2)
                                    .putLong("accessTokenExpiresAt", 9000 * 1000 + now2)
                                    .apply();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {

                    }
                });


    }
    public static interface CallBack{
        void onDataChanged(UavCondition uavCondition);
    }

}
